package utility;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class ForcedNamespaceSaxIntermediary implements ContentHandler {

   private ContentHandler handler;
   private String prefix;
   private String namespace;
   
   public ForcedNamespaceSaxIntermediary (ContentHandler handler, String prefix, String namespace) {
      this.handler = handler;
      this.prefix = prefix;
      this.namespace = namespace;
   }

   public void characters(char[] ch, int start, int length) throws SAXException {
      handler.characters(ch, start, length);
   }

   public void endDocument() throws SAXException {
      handler.endPrefixMapping(prefix);
      handler.endDocument();
   }

   public void endElement(String uri, String localName, String qName)
         throws SAXException {
      handler.endElement(uri, localName, qName);
   }

   public void endPrefixMapping(String prefix) throws SAXException {
      handler.endPrefixMapping(prefix);
   }

   public void ignorableWhitespace(char[] ch, int start, int length)
         throws SAXException {
      handler.ignorableWhitespace(ch, start, length);
   }

   public void processingInstruction(String target, String data)
         throws SAXException {
      handler.processingInstruction(target, data);
   }

   public void setDocumentLocator(Locator locator) {
      handler.setDocumentLocator(locator);
   }

   public void skippedEntity(String name) throws SAXException {
      handler.skippedEntity(name);
   }

   public void startDocument() throws SAXException {
      handler.startDocument();
      handler.startPrefixMapping(prefix, namespace);
   }

   public void startElement(String uri, String localName, String qName,
         Attributes atts) throws SAXException {
      
      AttributesImpl attributes = new AttributesImpl(atts);
      
      for (int i = 0; i < attributes.getLength(); ++i) {
         
         // Skip attributes without prefixes
         if (!attributes.getLocalName(i).contains(prefix + ":"))
            continue;
         
         String[] components = attributes.getLocalName(i).split(":");
         attributes.setAttribute(i, namespace, components[1], prefix + ":" + components[1], attributes.getType(i), attributes.getValue(i));
      }
      
      handler.startElement(uri, localName, qName, attributes);
   }

   public void startPrefixMapping(String prefix, String uri)
         throws SAXException {
      handler.startPrefixMapping(prefix, uri);
   }
   
   
}
